package cn.submarine;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;
import java.util.Arrays;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class World extends JPanel{
    public static final int WIDTH = 641;//窗口的宽
    public static final int HEIGHT = 479;//窗口的高

    public static final int RUNNING  = 0;//world类窗口运行状态
    public static final int GAME_OVER = 1;
    private int state = RUNNING;//默认为运行状态

    private BattleShip battleShip = new BattleShip();
    private SeaObject[] submarine = {};
    private Bomb[] bombs = {};
    private Mine[] mines = {};


    public void paint(Graphics graphics){
        switch (state){
            case GAME_OVER:
                Images.gameover.paintIcon(null,graphics,0,0);
                break;
            case RUNNING:
                Images.sea.paintIcon(null,graphics,0,0);//海洋背景固定
                battleShip.paintImage(graphics);//获取战舰图片
                for (int i=0;i< submarine.length;i++){
                    submarine[i].paintImage(graphics);
                }
                for (int i=0;i< bombs.length;i++){
                    bombs[i].paintImage(graphics);
                }
                for (int i=0;i< mines.length;i++){
                    mines[i].paintImage(graphics);
                }

                graphics.drawString("score："+score,200,20);
                graphics.drawString("life："+battleShip.getLife(),200,30);

        }
    }

    public SeaObject nextSubmarine(){//生成潜艇（侦查、鱼雷、水雷）
        Random rand = new Random();
        int type = rand.nextInt(20);
        if (type < 10) {
            return new ObserveSubmarine();
        }else if (type < 15){
            return new TorpedoSubmarine();
        }else {
            return new MineSubmarine();

        }
    }

    private int subEnterIndex = 0;
    public void submarineEnterAction(){//潜艇入场；此方法会被action（）调用，故10毫秒执行一次
        subEnterIndex++;
        if (subEnterIndex%40==0){//每400毫秒走一次
            SeaObject obj = nextSubmarine();
            submarine = Arrays.copyOf(submarine,submarine.length+1);//扩容
            submarine[submarine.length-1] = obj;
        }
    }

    private int mineEnterIndex = 0;
    public void mineEnterAction(){//水雷入场
        mineEnterIndex++;
        if (mineEnterIndex%100==0){//100*10毫秒运行一次
            for (int i=0;i<submarine.length;i++){
                if (submarine[i] instanceof MineSubmarine) {
                    MineSubmarine ms = (MineSubmarine) submarine[i];
                    Mine obj = ms.shootMine();
                    mines = Arrays.copyOf(mines,mines.length+1);
                    mines[mines.length-1] = obj;
                }
            }
        }
    }

    public void moveAction(){//每10毫秒走一次
        for (int i=0;i<submarine.length;i++){
            submarine[i].move();
        }
        for (int i=0;i<mines.length;i++){
            mines[i].move();
        }
        for (int i=0;i<bombs.length;i++){
            bombs[i].move();
        }
    }

    public void outOfBoundsAction(){
        for (int i=0;i<submarine.length;i++){//判断三种潜艇是否越界，越界则删除
            if (submarine[i].isOutBounds() || submarine[i].isDead()){//遍历数组，找出越界或者死了的元素
                submarine[i] = submarine[submarine.length-1];//将越界元素和数组最后一个元素替换
                submarine = Arrays.copyOf(submarine,submarine.length-1);//缩容
            }
        }
        for (int i=0;i<mines.length;i++){
            if (mines[i].isOutBounds() || mines[i].isDead()){
                mines[i] = mines[mines.length-1];
                mines = Arrays.copyOf(mines,mines.length-1);
            }
        }
        for (int i=0;i<bombs.length;i++){
            if (bombs[i].isOutBounds() || bombs[i].isDead()) {
                bombs[i] = bombs[bombs.length-1];
                bombs = Arrays.copyOf(bombs,bombs.length-1);
            }
        }

    }

    private int score = 0;//玩家得分
    public void bombBangAction(){
        //此方法每10毫秒走一次
        for (int i=0;i<bombs.length;i++){
            Bomb b = bombs[i];
            for (int j=0;j<submarine.length;j++){
                SeaObject s = submarine[j];
                if (b.isLive() && s.isLive() && s.isHit(b)){
                    b.goDead();
                    s.goDead();

                    if (s instanceof EnemyScore) {
                        EnemyScore es = (EnemyScore) s;
                        score += es.getScore();
                    }
                    if (s instanceof EnemyLive) {
                        EnemyLive el = (EnemyLive) s;
                        int num = el.getLive();
                        battleShip.addLife(num);
                    }
                }
            }
        }
    }

    public void mineBangAction(){//水雷与战舰的碰撞
        for (int i=0;i<mines.length;i++){
            Mine m = mines[i];
//            System.out.println(11111);//查看程序是否进到这个方法
            if (m.isLive() && battleShip.isLive() && m.isHit(battleShip)) {
                m.goDead();
                battleShip.subtractLife();
            }
//            System.out.println(battleShip.getLife());
        }
    }

    public void checkGameOverAction(){//每10毫秒运行一次
        if (battleShip.getLife() <= 0) {
            state = GAME_OVER;
        }
    }

    public void action(){//启动程序的执行
        KeyAdapter k = new KeyAdapter() {
            @Override
            //重写KeyReleased（）按键抬起事件
            public void keyReleased(KeyEvent e) {//当按键抬起时会自动执行
                if (e.getKeyCode()==KeyEvent.VK_SPACE){//判断若按键是空格键
                    Bomb obj = battleShip.shootBomb();
                    bombs = Arrays.copyOf(bombs,bombs.length+1);
                    bombs[bombs.length-1] = obj;
                }
                if (e.getKeyCode()==KeyEvent.VK_LEFT){
                    battleShip.moveLeft();
                }else if (e.getKeyCode()==KeyEvent.VK_RIGHT){
                    battleShip.moveRight();
                }
            }
        };//键盘侦听器
        this.addKeyListener(k);//添加侦听


        Timer timer = new Timer();//定时器对象
        int interval = 10;//定时间隔（以毫秒为单位）
        timer.schedule(new TimerTask() {
            public void run() {// run()代表定时干的事儿（每interal毫秒自动执行）
                submarineEnterAction();
                mineEnterAction();
                moveAction();
                outOfBoundsAction();
                bombBangAction();
                mineBangAction();//水雷与战舰的碰撞
                checkGameOverAction();//检测游戏结束
//                System.out.println(battleShip.state);
                repaint();//重新画
                }
        }, interval, interval);
    }

    public static void main(String[] args) {
        int[] score = new int[]{2,34,5,3};
        int[] scor = {2,34,5,3};

        JFrame frame = new JFrame();
        World world = new World();
        world.setFocusable(true);
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH+16,HEIGHT+39);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);// 1、程序走到这里时会自动调用paint()方法；2、将窗口设置成可见

        world.action();//启动程序的执行








    }
}
